﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Dapper;
using MySql.Data.MySqlClient;
using HelloApp2.Model;

namespace HelloApp2.Controllers
{
    //[Route("api/[controller]")]
    [Route("api/")]
    public class BookController : Controller
    {
        private readonly IDbConnection _connection;
        public BookController() {
            _connection = DapperService.MySqlConnection();
        }

        [HttpGet("books")]
        public ActionResult Get()
        {
            var result = _connection.Query<Object>("select * from book");
            if (result == null) {
                return NotFound();
            }

            return Ok(result);
        }

        [HttpGet("book/{id}")]
        public ActionResult Get(int id)
        {
            var result = _connection.QueryFirst("select * from book where id=@id", new { id = id });
            if (result == null)
            {
                return NotFound();
            }

            return Ok(result);
        }

        /// <summary>
        /// 删除图书
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("book/{id}")]
        public ActionResult Delete(int id)
        {
            var effectRow = _connection.Execute("delete from book where id=@id", new { id = id });
            if (effectRow > 0)
            {
                return new JsonResult("删除成功");
            }
            else {
                return new JsonResult("删除失败");
            }
        }

        /// <summary>
        /// 添加图书
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("AddBook")]
        public ActionResult AddBook(Book book)
        {
            string sql = @"insert into book(Id, Name, Author) values (@Id, @Name, @Author) "; 
            var effectRow = _connection.Execute(sql, new { Id = book.Id, Name = book.Name, Author = book.Author });
            if (effectRow > 0)
            {
                return new JsonResult("添加成功");
            }
            else
            {
                return new JsonResult("添加失败");
            }
        }

        /// <summary>
        /// 更新图书
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("updateBook")]
        public ActionResult updateBook(Book book)
        {
            string sql = @"update book set Name=@Name, Author=@Author where Id=@Id ";
            var effectRow = _connection.Execute(sql, new { Id = book.Id, Name = book.Name, Author = book.Author });
            if (effectRow > 0)
            {
                return new JsonResult("更新成功");
            }
            else
            {
                return new JsonResult("更新失败");
            }
        }
    }
}

